package com.zhongketech.sunflower.sv;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.AvoidXfermode;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import com.zhongketech.sunflower.Constant;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.R;
import com.zhongketech.sunflower.adapter.FcsContact;
import com.zhongketech.sunflower.transport.Action;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.model.Applications;
import com.zhongketech.sunflower.transport.model.DaoSession;
import com.zhongketech.sunflower.transport.model.EyeProtect;
import com.zhongketech.sunflower.transport.model.MyRequest;
import com.zhongketech.sunflower.transport.model.MySupervision;
import com.zhongketech.sunflower.transport.model.SmsCode;
import com.zhongketech.sunflower.transport.model.Supervision;
import com.zhongketech.sunflower.transport.model.SupervisionDao;
import com.zhongketech.sunflower.transport.model.TestMySupervision;
import com.zhongketech.sunflower.transport.model.TestSupervision;
import com.zhongketech.sunflower.transport.model.Times;
import com.zhongketech.sunflower.transport.model.User;
import com.zhongketech.sunflower.transport.model.UserDao;
import com.zhongketech.sunflower.utils.DataString;
import com.zhongketech.sunflower.utils.Root;
import com.zhongketech.sunflower.utils.Utilities;

public class SvManager {

	private static final String TAG = "SvManager";
	private static SvManager instance = new SvManager();
	private MySupervision mySupervision;
	private Supervision ActivateSv = null;
	private List<Applications> disableApp = new ArrayList<Applications>();
	private Thread screenCheckThread = null;
	private EyesManager eyesManager = new EyesManager();

	private String[] appWhiteList = {"com.zhongketech",
			"com.cyanogenmod.trebuchet",
			"com.android.",
			"com.system."
	};

	private DaoSession ds;


	private SvManager()  
	{
		ds = MyApplication.getInstance().getSupervisonsDaoSession();
		screenOnListener(new ScreenStateListener() {

			@Override
			public void onScreenOn() {
				// TODO Auto-generated method stub
				Log.e(TAG," onScreenOn");
			}

			@Override
			public void onScreenOff() {
				// TODO Auto-generated method stub
				Log.e(TAG," onScreenOff");
			}
		});
	}

	synchronized public static SvManager getInstance()
	{
		return instance;
	}

	synchronized public void check()
	{
		new Thread(new Runnable() {
			public void run() {
				Looper.prepare();
				//				//				MySupervision  mySupervision = null;
				//				MySupervision msvNet = new Action().supervisions();
				//				if(null == msvNet)
				//				{
				//					MyToast.getInstance().show("没有可控制项");
				//				}
				//				else
				//				{
				//					//					LogUtil.i(TAG,"MySupervisionId: "+msvNet.getMySupervisionId());
				//					//					List<MySupervision> msvDbList = ds.getMySupervisionDao().loadAll();
				//					//					MySupervision msvDb = null;
				//					//					if(null != msvDbList && msvDbList.size() > 0)
				//					//					{
				//					//						msvDb = msvDbList.get(0);
				//					//						LogUtil.i(TAG,"msvDb MySupervisionId: "+msvDb.getMySupervisionId());
				//					//						List<Supervision> svListDb = msvDb.getSupervisons();
				//					//						for(int i = 0;i < svListDb.size();i ++)
				//					//						{ 
				//					//							for(int j = 0;j < msvNet.getSupervisons().size();j ++)
				//					//							{
				//					//								if(svListDb.get(i).getId() != null && )
				//					//							}
				//					//						}
				//					//					}
				//					//					else
				//					//					{
				//					//						LogUtil.i(TAG,"msvDb null now insert");
				//					//						ds.getMySupervisionDao().deleteAll();
				//					//						ds.getMySupervisionDao().insertOrReplace(msvNet);
				//					//					}
				//
				setMySupervision(new Action().supervisions());
				//					test(msvNet);
				//				}



				//				test(new Action().testsupervisions());

			}
		}).start();
	}

	private void test(TestMySupervision msv)
	{
		LogUtil.i(TAG,"msv: "+msv);
		List<TestSupervision> sv = msv.getSupervisons();
		LogUtil.i(TAG,"sv: "+sv);
		if(null != sv)
		{
			for(int i = 0;i < sv.size();i ++)
			{
				LogUtil.i(TAG,"sv: "+sv.get(i).getTitle());
				LogUtil.i(TAG,"sv: "+sv.get(i).getId());


				//				for(int j = 0;null != sv.get(i).getTime_segments() && j < sv.get(i).getTime_segments().size();j++)
				//				{
				//					LogUtil.i(TAG,"sv["+j+"]: "+sv.get(i).getTime_segments().get(j).getStart_at());	
				//					LogUtil.i(TAG,"sv["+j+"]: "+sv.get(i).getTime_segments().get(j).getEnd_at());	
				//				}
				LogUtil.i(TAG,"sv app: "+sv.get(i).getApplication());
				//				LogUtil.i(TAG,"sv: "+sv.get(i).getPriority());
				//				LogUtil.i(TAG,"sv call: "+sv.get(i).getCall());
				//				LogUtil.i(TAG,"sv eyes: "+sv.get(i).getEyes_protect());
				//				LogUtil.i(TAG,"sv net: "+sv.get(i).getNetwork());
			}
		}
		else
		{
			LogUtil.i(TAG,"sv null !!");
		}
	}

	synchronized public MySupervision getMySupervision() {
		return mySupervision;
	}

	synchronized public void setMySupervision(MySupervision mySupervision) {
		this.mySupervision = mySupervision;
		//		ds.getMySupervisionDao().update(this.mySupervision);;

	}

	synchronized public Supervision getActivateSv()
	{
		return ActivateSv;
	}

	static final boolean logEnable = false;
	synchronized public Supervision activateSvHandle()
	{
		if(logEnable)
			LogUtil.i(TAG,"getActivateSv");
		//		check(); 
		if(null != mySupervision && null != mySupervision.getSupervisons())
		{
			Supervision sv = null;
			for(int i = 0;i < mySupervision.getSupervisons().size();i ++)
			{
				sv = mySupervision.getSupervisons().get(i);
				//一键控制在总是生效
				if("one_key".equals(sv.getType()) && sv.getEnable())
				{
					ActivateSv =  sv;
					return ActivateSv;
				}
			}

			List<Supervision> activateList = new ArrayList<Supervision>();
			activateList.clear();
			for(int i = 0;i < mySupervision.getSupervisons().size();i ++)
			{
				sv = mySupervision.getSupervisons().get(i);
				{
					int[] p = sv.getPeriod();
					int way = DataString.getInstance().getmWay();
					if(logEnable)
						LogUtil.i(TAG,"this way:"+way);
					for(int j = 0; null != p && j < p.length;j ++)
					{
						//星期是否符合
						if(logEnable)
							LogUtil.i(TAG,"Period["+j+"]"+p[j]);
						if(way == p[j])
						{
							List<Times> times = sv.getTime_segments();
							for(int k = 0; null != times && k < times.size();k ++)
							{
								Times t = times.get(k);
								//时间是否符合
								int min = DataString.getInstance().getMinOfDay();
								if(logEnable)
									LogUtil.i(TAG,"this min:"+min);
								if(logEnable)
									LogUtil.i(TAG,"times["+k+"]"+t);
								if(t != null)
								{
									if(logEnable)
										LogUtil.i(TAG,"times["+k+"] start:"+t.getStart_at());
									if(logEnable)
										LogUtil.i(TAG,"times["+k+"] end:"+t.getEnd_at()); 
									if(min > t.getStart_at() && min < t.getEnd_at())
									{
										if(logEnable)
											LogUtil.i(TAG,"find the Activate Supervisons:"+sv.getTitle());
										activateList.add(sv);
										ActivateSv =  sv;  
										return ActivateSv;
									}
								}
							}
						}
					}

				}
			}

			ActivateSv =  null;  

		}
		return ActivateSv;
	}

	public EyesManager getEyesManager()
	{
		return eyesManager;
	}

	synchronized public boolean isLock()
	{
		activateSvHandle();
		if(null != ActivateSv && null != ActivateSv.getScreen_lock())
		{
			//			LogUtil.i(TAG,"ActivateSv.getScreen_lock().getEnable():"+ActivateSv.getScreen_lock().getEnable());
			return ActivateSv.getScreen_lock().getEnable();
		}

		return false;
	}

	synchronized public String appEnable()
	{

		LogUtil.i(TAG,"ActivateSv:"+ActivateSv);
		if(null != ActivateSv && null != ActivateSv.getApplication())
		{
			return ActivateSv.getApplication().getEnable();
		}

		return Constant.APP_ENABLE_ALL;
	}

	synchronized public boolean isWebEnable()
	{
		if(null != ActivateSv && null != ActivateSv.getNetwork())
		{
			LogUtil.i(TAG,"ActivateSv.getNetwork().getEnable():"+ActivateSv.getNetwork().getEnable());
			return ActivateSv.getNetwork().getEnable();
		}
		return false;
	}

	private void screenOnListener(final ScreenStateListener listener) {

		if(null != screenCheckThread && screenCheckThread.isAlive())
		{
			Log.d(TAG, "screenCheckThread exite:" + screenCheckThread);
			return;
		}

		screenCheckThread = new Thread(new Runnable() {
			public void run() {
				Looper.prepare();
				boolean oldScreenState = true;
				boolean nowScreenState = true;
				//				boolean isEyeLock = false;
				Long playTime = (long) 0;
				//				Long restTime = (long) 0;

				while(true)
				{
					EyeProtect ep = null;
					//前提是眼睛保护开启
					if(null == ActivateSv)
					{
						continue;
					}
					ep = ActivateSv.getEyes_protect();
					if(null == ep)
					{
						continue;
					}

					if(!ep.getEnable())
					{
						continue;
					}

					Long curTime = System.currentTimeMillis();
					Method mReflectScreenState = null;
					try {
						mReflectScreenState = PowerManager.class.getMethod("isScreenOn",
								new Class[] {});
					} catch (NoSuchMethodException nsme) {
						Log.d(TAG, "API < 7," + nsme);
					}

					if(null != mReflectScreenState)
					{
						PowerManager manager = (PowerManager) MyApplication.getInstance().getApplicationContext()
								.getSystemService(Activity.POWER_SERVICE);
						try {
							nowScreenState = (Boolean) mReflectScreenState.invoke(manager);
						} catch (Exception e) {
							Log.d(TAG, "screenOnListener e:" + e);
							nowScreenState = false;
						}	
					}

					Log.d(TAG, "playTime:" + playTime/1000 + "s curTime:"+curTime/1000+"s restTime:"+
							(eyesManager.resetTime * 1000-curTime)/1000+"s");

					/*在眼睛保护开启的情况下，下面两种情况可以让用户玩
					 * 1、锁屏 并且大于onstant.REST_PLAY_TIME
					 * 2、到了保护时间并且大于设定需强制休息的时间
					 * 
					 */
					if((!oldScreenState && eyesManager.resetTime > Constant.REST_PLAY_TIME || 
							eyesManager.isEnable && eyesManager.resetTime > ep.getRest_time() * 60 * 1000))
					{
						eyesManager.isEnable = false;
						eyesManager.resetTime = eyesManager.resetTime + Constant.SCREEN_CHECK_INTERVAL/1000;
						//只有可以玩了才能清空玩的时间
						playTime = (long) 0;
						Log.e(TAG,"可以玩了");
						MyToast.getInstance().show("可以玩了");
						eyesManager.needResetTime = 0;
					}

					/*
					 * 只有在非锁屏已经非强制休息时，才开始统计玩的时间
					 * 
					 * 
					 */
					if(oldScreenState && !eyesManager.isEnable)
					{
						//只要在开锁并且不再锁定时，休息时间即清零
						eyesManager.resetTime = (long) 0;
						playTime = playTime + Constant.SCREEN_CHECK_INTERVAL ;
						//判断是否需要强制休息
						if(null != ep)
						{
							if(ep.getEnable() && playTime > ep.getUse_time() * 60)
							{
								eyesManager.needResetTime = ep.getRest_time() * 60;
								Log.e(TAG,"强制休息");
								MyToast.getInstance().show("强制休息");
								eyesManager.isEnable = true;
								MyToast.getInstance().EyesLockPhone();
								//								eyesManager.resetTime = (long) 0;
							}
						}
					}

					//屏幕状态发生改变
					if(oldScreenState != nowScreenState)
					{
						Log.d(TAG, "screenlock changge " + oldScreenState+" to "+ nowScreenState);
						oldScreenState = nowScreenState;			
						//开锁
						if(nowScreenState)
						{
							eyesManager.resetTime = (long) 0;
						}
						//锁屏
						else 
						{

						}
					}

					try {
						Thread.sleep(Constant.SCREEN_CHECK_INTERVAL * 1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		});

		screenCheckThread.start();
	}

	synchronized public boolean eyesEnable()
	{
		if(null != ActivateSv && null != ActivateSv.getEyes_protect())
		{
			LogUtil.i(TAG,"ActivateSv.getEyes_protect().getEnable()"+ActivateSv.getEyes_protect().getEnable());
			return ActivateSv.getEyes_protect().getEnable();
		}
		return false;
	}

	synchronized public boolean isPhoneEnable()
	{
		if(null != ActivateSv && null != ActivateSv.getCall())
		{
			LogUtil.i(TAG,"ActivateSv.getCall().getEnable()"+ActivateSv.getCall().getEnable());
			return ActivateSv.getCall().getEnable();
		}
		return false;
	}

	synchronized public boolean isSmsEnable()
	{
		if(null != ActivateSv && null != ActivateSv.getSms())
		{
			LogUtil.i(TAG,"ActivateSv.getSms().getEnable()"+ActivateSv.getSms().getEnable());
			return ActivateSv.getSms().getEnable();
		}
		return false;
	}

	synchronized public String[] eyesTime()
	{
		if(null != ActivateSv && null != ActivateSv.getEyes_protect() && ActivateSv.getEyes_protect().getEnable())
		{
			String[] time = { ActivateSv.getEyes_protect().getUse_time().toString(), ""+ActivateSv.getEyes_protect().getRest_time().toString()};
			return time;
		}

		return null;
	}

	synchronized public boolean isOpen(String packageName)
	{
		//全局应用白名单
		for(int j = 0;null != packageName && j < appWhiteList.length;j ++)
		{
			if(packageName.startsWith(appWhiteList[j]))
			{
				new Thread(new Runnable() {
					public void run() {
						//						Looper.prepare();
						activateSvHandle();
					}
				}).start();

				return true;
			}
		}

		Supervision sv = activateSvHandle();
		if(null != sv && null != packageName)
		{
			String appEnable = Constant.APP_ENABLE_ALL;
			try {
				if(null != sv.getApplication())
				{
					appEnable = sv.getApplication().getEnable();
					LogUtil.i(TAG,"appEnable :"+appEnable+" Title:"+ sv.getTitle());

					LogUtil.i(TAG,"appEnable:"+appEnable);
					if(Constant.APP_LIST.equals(appEnable))
					{
						List<Applications> appList = sv.getApplication().getApplications();
						for(int i = 0;null != appList && i < appList.size();i ++)
						{
							LogUtil.i(TAG, "appEnable:"+appEnable+" id:"+appList.get(i).getId());
							if(packageName.equals(appList.get(i).getId()))
								//								if(packageName.equals(appList.get(i).getApp_name()))
							{
								if(Constant.APP_ENABLE_ALL.equals(appEnable))
								{
									return false;
								}
								else if(Constant.APP_LIST.equals(appEnable))
								{
									if(appList.get(i).getEnable())
									{
										return false;
									}
								}
							}
						}
					}
					else if(Constant.APP_DISABLE_ENABLE.equals(appEnable))
					{
						LogUtil.i(TAG,"本策略中应用全部禁止打开");
						return false;
					}
					else
					{
						LogUtil.i(TAG,"本策略中应用全部可使用");
						return true;
					}
				}
				else
				{
					LogUtil.i(TAG,"sv:"+sv+" packageName"+packageName );
				}
			}
			catch (Exception e) {
				// TODO: handle exception
				LogUtil.i(TAG,"Exception e"+e);
			}
		}
		else
		{
			LogUtil.i(TAG,"目前没有策略生效");
		}

		return true;
	}

	synchronized public List<Applications> getDisableListApp() {

		Supervision sv = ActivateSv;
		if(null != disableApp && null != sv && null != sv.getApplication()
				&& null != sv.getApplication().getApplications())
		{
			List<Applications> list = sv.getApplication().getApplications();
			disableApp.clear();
			for(int i = 0;i < list.size();i ++)
			{
				if(list.get(i).getEnable())
				{
					disableApp.add(list.get(i));
				}
			}
			return disableApp;
		}

		return null;
	}

}
